import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from "path"
import path from 'path'

// https://vite.dev/config/ 
export default defineConfig({
  plugins: [vue()],
  base: '/nccloud/resources/sip',
  resolve: {
    alias: {
      // '@': resolve(__dirname, './src') // 兼容src目录下的文件夹可通过 @/components/HelloWorld.vue写法 // 设置路径
      '~': path.resolve(__dirname, './'),
      // 设置别名
      '@': path.resolve(__dirname, './src')
    }
  },
  // vite 相关配置
  server: {
    port: 3308,
    host: true,
    open: true,
    proxy: {
      // 确保 /nccloud/resources/sip 不走代理，直接访问本地资源
      '/nccloud/resources/sip': {
        // 使用 bypass 函数来完全跳过代理
        bypass: (req, res) => {
          console.log(`[Bypass Proxy] Request to ${req.url} bypassed proxy`);
          // 返回一个非空值，表示跳过代理，直接由 Vite 服务器处理
          return req.url;
        }
      },
      // 将所有 /service/ 开头的请求代理到 http://localhost:9000
      '/service': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        // rewrite: (path) => path.replace(/^\/service/, ''),
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            let body = [];
            req.on('data', (chunk) => {
              body.push(chunk);
            }).on('end', () => {
              body = Buffer.concat(body).toString();
              console.log(`[Proxy] ${req.method} ${req.url} -> ${proxyReq.getHeader('host')}${proxyReq.path}`);
              console.log(`Request Body: ${body}`);
            });
          });
        }
      },//解决NCC代理问题 - 只对后端API请求生效
      // 代理 /nccloud/resources/platform 请求
      '/nccloud': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log(`[Platform API Proxy] ${req.method} ${req.url} -> ${proxyReq.getHeader('host')}${proxyReq.path}`);
          });
        }
      },
      // 通配符代理：代理所有其他请求（不包括上面明确指定的路径）
      '*': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log(`[Wildcard API Proxy] ${req.method} ${req.url} -> ${proxyReq.getHeader('host')}${proxyReq.path}`);
          });
        }
      }
    }
  },
  css:{
    preprocessorOptions: {
      scss: {
         additionalData: '', // 全局公共样式
         charset:false
      }
   }
  }
})